﻿using Microsoft.Extensions.Options;
using Volo.Abp.Caching;
using Volo.Abp.DependencyInjection;
using Volo.Abp.MultiTenancy;

namespace Xms.Abp.Caching;

[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(IDistributedCacheKeyNormalizer))]
public class XmsCacheKeyNormalizer : IDistributedCacheKeyNormalizer, ITransientDependency
{
    public const string GlobalKeyPrefix = "Global:";

    protected ICurrentTenant CurrentTenant { get; }

    protected AbpDistributedCacheOptions DistributedCacheOptions { get; }

    public XmsCacheKeyNormalizer(
        ICurrentTenant currentTenant,
        IOptions<AbpDistributedCacheOptions> distributedCacheOptions)
    {
        CurrentTenant = currentTenant;
        DistributedCacheOptions = distributedCacheOptions.Value;
    }

    public virtual string NormalizeKey(DistributedCacheKeyNormalizeArgs args)
    {
        var normalizedKey = $"{args.CacheName}:{DistributedCacheOptions.KeyPrefix}{args.Key}";

        if (!args.IgnoreMultiTenancy)
        {
            if (CurrentTenant.Id.HasValue)
            {
                normalizedKey = $"Tenant_{CurrentTenant.Id.Value:n}:{normalizedKey}";
            }
            else
            {
                normalizedKey = $"Host:{normalizedKey}";
            }
        }
        else
        {
            return GlobalKeyPrefix + normalizedKey;
        }

        return normalizedKey;
    }
}
